import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 所有的任务列表
    list: [],
    // 文本框的内容
    inputVal: '',
    // 下一项的ID
    nextId: '-1',
    // 当前显示的按钮选项卡索引
    viewKey: 0
  },
  mutations: {
    initList (state, list) {
      state.list = list
      state.nextId = list.length
    },
    setInputVal (state, newVal) {
      state.inputVal = newVal
    },
    // 添加一个列表项
    addItem (state) {
      const obj = {
        id: state.nextId,
        info: state.inputVal,
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputVal = ''
    },
    // 根据id去删除对应列表
    removeItem (state, id) {
      // 1. 根据id查找对应项的索引
      const index = state.list.findIndex(x => x.id === id)
      // 2. 调用splice删除对应项
      if (index !== -1) {
        state.list.splice(index, 1)
      }
    },
    // 根据id查找对应项并改变其完成状态
    changeItemDone (state, params) {
      const i = state.list.findIndex(x => x.id === params.id)
      state.list[i].done = params.status
    },
    // 清除已完成任务项
    cleanDone (state) {
      const newList = state.list.filter(item => item.done === false)
      state.list = newList
    },
    // 改变当前展示的选项按钮视图
    changeViewIndex (state, index) {
      state.viewKey = index
    }
  },
  actions: {
    getList (content) {
      axios.get('/list.json').then(({ data }) => {
        content.commit('initList', data)
      })
    }
  },
  modules: {
  },
  getters: {
    // 显示未完成条数
    unDoneLength (state) {
      const newList = state.list.filter(x => !x.done)
      return newList.length
    },
    // 根据不同选项卡索引选择显示不同的任务
    showListByViewKey (state) {
      if (state.viewKey === 1) {
        // 显示未完成
        return state.list.filter(x => !x.done)
      }

      if (state.viewKey === 2) {
        // 显示已完成
        return state.list.filter(x => x.done)
      }

      // 显示全部
      return state.list
    }
  }
})
